<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Service\Statistics;

use App\Models\BeanSetting;
use App\Models\GroupOrder;
use App\Models\MemberTopupOrder;
use App\Models\OrderBeanRewards;
use App\Models\PerformanceMember;
use App\Models\ProductOrder;
use App\Models\RewardTransaction;
use App\Models\ThePriceOfGreenBean;
use App\Models\User;
use App\Models\UserBeanPackages;
use App\Models\UserRewardAccount;
use App\Models\UserTotalRevenue;
use App\Models\WalletTransaction;
use App\Models\Withdrawal;
use App\Service\BaseService;
use App\Service\Setting\BeanSettingService;
use Illuminate\Support\Facades\Cache;

class StatisticsService extends BaseService
{
    public function myFan(User $user): array
    {
        $fan = $user->queryDescendants()
            ->with(['totalRevenue' => function ($query) {
                $query->select('id', 'user_id', 'self');
            }])
            ->select('id', 'name', 'profile', 'telephone', 'member_level', 'distance', 'created_at')
            ->get();
        $userTotal = UserTotalRevenue::query()
            ->whereIn('user_id', $fan->pluck('id'))
            ->get();
        $productOrder = ProductOrder::query()
            ->select('user_id', 'id', 'total_amount', 'status', 'created_at')
            ->whereIn('user_id', $fan->pluck('id'))
            ->where('status', '>', 2)
            ->get();
        $groupOrder = GroupOrder::query()
            ->select('user_id', 'id', 'amount', 'status', 'created_at')
            ->whereIn('user_id', $fan->pluck('id'))
            ->where('status', '>', 2)
            ->get();
        $directPush = $fan->where('distance', 1);
        $today_consumption = bcadd(
            $productOrder->where('created_at', '>', now()->startOfDay())->sum('total_amount'),
            $groupOrder->where('created_at', '>', now()->startOfDay())->sum('amount'),
            2
        );

        $month_consumption = bcadd(
            $productOrder->where('created_at', '>', now()->startOfMonth())->sum('total_amount'),
            $groupOrder->where('created_at', '>', now()->startOfMonth())->sum('amount'),
            2
        );

        $performanceRecord = PerformanceMember::query()
            ->where('user_id', $user->id)
            ->first();

        $smallDepartment = $performanceRecord->small_teams_sum ?? 0;
        $totalConsumption = $userTotal->sum('self');

        $direct_push = $fan->where('distance', 1)->map(function ($item) {
            $ids = $item->queryDescendants()->pluck('id');
            $data = UserTotalRevenue::query()->where('user_id', $item->id)->first();
            $item['count'] = $ids->count();
            $item['self'] = $data->self ?? 0;
            $item['value'] = $data->value ?? 0;
            $item['product'] = $data->product ?? 0;
            $item['group'] = $data->group ?? 0;
            $item['group_team'] = $data->group_team ?? 0;
            $item['product_team'] = $data->product_team ?? 0;
            return $item;
        });

        return [
            'smallDepartment' => $smallDepartment,   //小部门之和
            'totalConsumption' => $totalConsumption,  //粉丝累计总消费
            'fan_count' => $fan->count(),            //粉丝数量
            'unconsumed' => $userTotal->where('self', 0)->count(), //未消费粉丝
            'directly' => $directPush->count(),      //直推粉丝
            'indirect' => $fan->where('distance', '<>', 1)->count(),  //间接粉丝
            'today' => $fan->where('created_at', '>', now()->startOfDay())->count(), //今日新增粉丝
            'today_consumption' => $today_consumption,   //今日消费
            'month' => $fan->where('created_at', '>', now()->startOfMonth())->count(), //本月新增
            'month_consumption' => $month_consumption,   //本月消费
            'direct_push' => $direct_push,
        ];
    }

    public function teamCenter(User $user): array
    {
        $userReward = UserRewardAccount::query()
            ->where('user_id', $user->id)
            ->first();
        $trans = RewardTransaction::query()
            ->where('user_id', $user->id)
            ->get();
        $package = UserBeanPackages::query()
            ->where('user_id', $user->id)
            ->where('status', 2)
            ->get();

        $order = OrderBeanRewards::query()
            ->where('user_id', $user->id)
            ->get();
        $w = Withdrawal::query()
            ->where('user_id', $user->id)
            ->get();

        return [
            'today' => round($trans
                ->where('created_at', '>', now()->startOfDay())
                ->where('change_type', 1)
                ->sum('amount'), 2),
            'month' => round($trans
                ->where('created_at', '>', now()->subMonth())
                ->where('change_type', 1)
                ->sum('amount'), 2),
            'total_balance' => $userReward->total_balance,
            'reward_balance' => $userReward->available_balance,   //奖励余额
            'withdrawn' => bcadd($package->sum('remaining_beans'), $order->sum('remaining_beans'), 2),  //待结算
            'withdrawal_in_progress' => round($w->where('status', 1)->sum('arrival_amount'), 2), //提现中
            'to_be_settled' => round($w->where('status', 2)->sum('arrival_amount'), 2),   //已提现
        ];
    }

    public function salesVolume() //销售额
    {
        $groupOrder = GroupOrder::query()->where('status', '>', 2)->sum('amount');
        $productOrder = ProductOrder::query()->where('status', '>', 2)->sum('total_amount');
        return [
            'group' => $groupOrder,
            'product' => $productOrder,
            'total' => bcadd($groupOrder, $productOrder, 2),
        ];
    }

    public function pointPrice()
    {
        $BeanStartPrice = BeanSettingService::make()->getSetting('BEAN_START_PRICE');
        $beanPercentage = BeanSettingService::make()->getSetting('BEAN_PERCENTAGE');
        $beanRiseOrFall = BeanSettingService::make()->getSetting('BEAN_RISE_OR_FALL');

        $now = now()->format('Y-m-d');
        $yesterday = now()->subDay()->format('Y-m-d');
        $tpob = ThePriceOfGreenBean::query()->get();
        if (blank($tpob)) {
            //初始化
            $yesterDayData[] = [
                'date' => now()->subDays(6)->format('Y-m-d'),
                'price' => $BeanStartPrice,
            ];
            for ($i = 5; $i > 0; --$i) {
                $yesterDayData[] = [
                    'date' => now()->subDays($i)->format('Y-m-d'),
                    'price' => $BeanStartPrice,
                ];
            }
            ThePriceOfGreenBean::query()->insert($yesterDayData);
            BeanSetting::query()->where('key', 'PRICE')->update([
                'value' => $BeanStartPrice,
            ]);
            Cache::forever('now_price', $BeanStartPrice);
            return $yesterDayData;
        }
        $nowDayData = $tpob->where('date', $now)->first();
        if (filled($nowDayData)) {
            return $tpob->take(-7)->values()->toArray();
        }
        $yesterDayData = $tpob->where('date', $yesterday)->first();
        $BeanStartPrice = $yesterDayData['price'];
        $BeanStartPrice = $this->getBeanStartPrice($BeanStartPrice, $beanPercentage, $beanRiseOrFall);

        BeanSetting::query()->where('key', 'PRICE')->update([
            'value' => $BeanStartPrice,
        ]);
        ThePriceOfGreenBean::query()->create([
            'date' => now()->format('Y-m-d'),
            'price' => $BeanStartPrice,
        ]);
        return ThePriceOfGreenBean::query()->take(-7)->get()->values()->toArray();
//        if (blank($tpob->where('date',$now)->first())) {
//            $yesterDayData = $tpob->where('date',$yesterday)->first()->toArray()??[];
//
//            if (blank($yesterDayData)) {
//
//            } else {
//                $BeanStartPrice = $yesterDayData['price'];
//            }
//            $yesterDayData = [$yesterDayData];
//
//            $BeanStartPrice = $this->getBeanStartPrice($BeanStartPrice, $beanPercentage, $beanRiseOrFall);
//
//            $yesterDayData[] = [
//                'date' => now()->format('Y-m-d'),
//                'price' => $BeanStartPrice,
//            ];
//            $tpob = $tpob->fresh();
//            ThePriceOfGreenBean::query()->insert($yesterDayData);
//            $res = collect($tpob)->take(-7)->values()->toArray();
//        } else {
//            $res = $tpob->take(-7)->values()->toArray();
//            $BeanStartPrice =  $tpob->where('date',$now)->first()->price;
//        }
//        BeanSetting::query()->where('key','PRICE')->update([
//            'value' => $BeanStartPrice,
//        ]);
//        Cache::forever('now_price', $BeanStartPrice);
//        return $res;
    }

    public function getNowPrice()
    {
        return BeanSetting::query()->where('key', 'PRICE')->first()->value;
    }

    public function geUserAccountAmount(User $user) //获取用户账户金额
    {
        return [
            'point' => $user->pointAccount->withdraw_points,
            'bean' => $user->beanAccount->available_beans,
            'wallet' => $user->walletAccount->balance,
            'reward' => $user->rewardAccount->available_balance,
        ];
    }

    public function getUserRecharge(User $user) //获取用户充值
    {
        return MemberTopupOrder::query()
            ->where('user_id', $user->id)
            ->where('review', 1)
            ->sum('amount');
    }

    public function getKcInfo(User $user)   //拼团释放通证  拼团待释放通证
    {
        $res = OrderBeanRewards::query()
            ->where('user_id', $user->id)
            ->where('remaining_beans', '>', 0)
            ->get();
        $total = $res->sum('total_reward_beans');
        $remaining_beans = round($res->sum('remaining_beans'), 2);
        return [
            'total' => $total,
            'release' => $remaining_beans,
            'released' => bcsub($total, $remaining_beans, 2),
        ];
    }

    public function consumption(User $user) //消费
    {
        $productOrder = ProductOrder::query()
            ->select('user_id', 'id', 'total_amount', 'status', 'created_at')
            ->where('user_id', $user->id)
            ->where('status', '>', 2)
            ->get();
        $groupOrder = GroupOrder::query()
            ->select('user_id', 'id', 'amount', 'status', 'created_at')
            ->where('user_id', $user->id)
            ->where('status', '>', 2)
            ->get();
        $product = $productOrder->sum('total_amount');
        $group = $groupOrder->sum('amount');
        $total = bcadd($product, $group, 2);
        $product = 0;
        if ($total > $product) {
            $product = bcdiv($group, $total, 2) * 100;
        }
        return [
            'product' => $product,
            'group' => $group,
            'total' => $total,
            'proportion' => $product,
        ];
    }

    public function transfer(User $user) //转账
    {
        $w = WalletTransaction::query()->where('user_id', $user->id)->get();

        return [
            'in' => $w->where('transaction_type', 5)->sum('amount'),
            'out' => $w->where('transaction_type', 4)->sum('amount'),
            'seeking' => $w->where('transaction_type', 6)->where('change_type', 2)->sum('amount'),
        ];
    }

    private function getBeanStartPrice($BeanStartPrice, $beanPercentage, $beanRiseOrFall)
    {
        $r = bcmul($BeanStartPrice, $beanPercentage, 2);
        switch ($beanRiseOrFall) {
            case 1:
                $r = $beanPercentage;
                $BeanStartPrice = bcadd($BeanStartPrice, $r, 2);
                break;
            case 2:
                $r = $beanPercentage;
                $BeanStartPrice = bcsub($BeanStartPrice, $r, 2);
                break;
            case 3:
                if (random_int(1, 2) == 1) {
                    $BeanStartPrice = bcadd($BeanStartPrice, $r, 2);
                } else {
                    $BeanStartPrice = bcsub($BeanStartPrice, $r, 2);
                }
                break;
        }
        return $BeanStartPrice;
    }
}
